package com.sunsy.authserver.beans;

import com.sunsy.authserver.enums.EApiErrorCode;
import com.sunsy.authserver.enums.IApiErrorCode;
import lombok.*;
import lombok.experimental.Accessors;

import java.util.Optional;

/**
 * rest接口统一返回体
 *
 * @author 孙思远
 * @date 2021/7/19
 */
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class R<T> {

    @Setter
    @Getter
    private long code;

    @Setter
    @Getter
    private String msg;

    @Setter
    @Getter
    private T data;

    public R(IApiErrorCode errorCode) {
        errorCode = Optional.ofNullable(errorCode).orElse(EApiErrorCode.FAILED);
        this.code = errorCode.getCode();
        this.msg = errorCode.getMsg();
    }

    public static <T> R<T> ok() {
        return restResult(null, EApiErrorCode.SUCCESS);
    }

    public static <T> R<T> ok(T data) {
        return restResult(data, EApiErrorCode.SUCCESS);
    }

    public static <T> R<T> ok(T data, String msg) {
        return restResult(data, EApiErrorCode.SUCCESS.getCode(), msg);
    }

    public static <T> R<T> failed() {
        return restResult(null, EApiErrorCode.FAILED);
    }

    public static <T> R<T> failed(String msg) {
        return restResult(null, EApiErrorCode.FAILED.getCode(), msg);
    }

    public static <T> R<T> failed(T data) {
        return restResult(data, EApiErrorCode.FAILED);
    }

    public static <T> R<T> failed(IApiErrorCode errorCode) {
        return restResult(null, errorCode);
    }

    public static <T> R<T> failed(IApiErrorCode errorCode, String msg) {
        return restResult(null, errorCode.getCode(), msg);
    }

    public static <T> R<T> restResult(T data, IApiErrorCode errorCode) {
        return restResult(data, errorCode.getCode(), errorCode.getMsg());
    }

    private static <T> R<T> restResult(T data, long code, String msg) {
        R<T> apiResult = new R();
        apiResult.setCode(code);
        apiResult.setData(data);
        apiResult.setMsg(msg);
        return apiResult;
    }

}
